import {ReturnValueHandler} from "../../../web/_ReturnValueHandler"
import {Component} from "../../anno/Component"
import {Order} from "../../anno/Order"
import {LogFactory} from "../../log"


@Component()
@Order(9999)
class DefaultPromiseHandler extends ReturnValueHandler {
  private logger = LogFactory.getLogger("DefaultPromiseHandler")

  canWrite(value: any): boolean {
    return value instanceof Promise
  }

  write(req: HttpRequest, res: HttpResponse, value: any): void {
    const promise: Promise<any> = value
    promise.then(ret => {
      console.log("ret", ret)
      res.end(ret)
    }).catch(err => {
      res.error(500, err.toString())
    }).finally(() => {
      this.logger.trace(`[${req.url}] finished a promise return type `)
    })
  }

}
